import { Db } from "../../main";
import {
  ChatType,
  IGetChatMessageRes,
  IGetMessageRes,
  IMessage,
  IMessageFileRes,
  IMessagePageInfo,
  MessageType,
} from "../../types/message";

// 插入消息
const insertSql = `
    INSERT OR IGNORE INTO message (uuid, ownerId, sendId, toId, groupId, sessionId, chatType, messageType,
                                   quotationId, aitIds, fileName, fileUrl, localPath, fileSize, content,
                                   callStatus, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`;

// 将单条消息转换为插入所需的值数组
function formatMessageRow(message: IMessage, ownerId: number): any[] {
  return [
    message.uuid,
    ownerId,
    message.sendId,
    message.toId,
    message.groupId ?? null,
    message.sessionId,
    message.chatType,
    message.messageType,
    message.quotationId ?? null,
    message.aitIds ?? null,
    message.fileName ?? null,
    message.fileUrl ?? null,
    message.localPath ?? null,
    message.fileSize ?? null,
    message.content ?? null,
    message.callStatus ?? null,
    message.status ?? 1,
  ];
}

// 插入消息
export function InsertMessages(messages: IMessage | IMessage[], ownerId: number): boolean {
  const stmt = Db.prepare(insertSql);
  const checkStmt = Db.prepare("SELECT 1 FROM message WHERE uuid = ? AND ownerId = ?");
  try {
    const rows = Array.isArray(messages) ? messages : [messages];
    const runInsert = Db.transaction((rows: IMessage[]) => {
      for (const msg of rows) {
        const exists = checkStmt.get(msg.uuid, ownerId);
        if (!exists) {
          stmt.run(formatMessageRow(msg, ownerId));
        }
      }
    });

    runInsert(rows);
    return true;
  } catch (error) {
    console.log("插入消息失败", error);
    return false;
  }
}

// 获取消息
export async function GetChatMessage(
  sessionId: string,
  ownerId: number,
  pageInfo: Partial<IMessagePageInfo>,
): Promise<IGetChatMessageRes> {
  const { pageSize = 15, page = 1 } = pageInfo;
  const offset = (page - 1) * pageSize;

  // 查询总数
  const countQuery = `SELECT COUNT(*) as count
                        FROM message
                        WHERE sessionId = ?
                          AND ownerId = ?`;
  const countResult = Db.prepare(countQuery).get(sessionId, ownerId) as { count: number };
  const total = countResult.count;
  const totalPage = Math.ceil(total / pageSize);

  // 查询分页数据
  let query = `
        SELECT *
        FROM message
        WHERE sessionId = ?
          AND ownerId = ?
        ORDER BY createdAt DESC
        LIMIT ? OFFSET ?
    `;
  const data = Db.prepare(query).all(sessionId, ownerId, pageSize, offset) as IGetMessageRes[];

  return {
    page,
    pageSize,
    totalPage,
    data,
  };
}

// 删除单条消息
export function DeleteMessageByOne(messageId: string, userId: number) {
  if (!messageId || !userId) {
    console.warn(`[SQLite] 无效参数 | messageId:${messageId} userId:${userId}`);
    return false;
  }

  try {
    const stmt = Db.prepare(`
            DELETE
            FROM message
            WHERE uuid = ?
              AND ownerId = ?
        `);

    const { changes } = stmt.run(messageId, userId);
    return changes > 0;
  } catch (error: any) {
    console.error(`[SQLite] 消息删除失败 | ${error.message}`, {
      messageId,
      userId,
      stack: error.stack,
    });
    return false;
  }
}

// 批量删除消息
export function DeleteMessagesByAll(
  userId: number,
  targetId: number, // friendId 或 groupId
  chatType: ChatType,
): boolean {
  if (!userId || !targetId) return false;

  try {
    const sql =
      chatType === ChatType.friend
        ? `DELETE
                   FROM message
                   WHERE ownerId = ?
                     AND (sendId = ? OR sendId = ?)`
        : `DELETE
                   FROM message
                   WHERE ownerId = ?
                     AND groupId = ?`;

    const params = chatType === ChatType.friend ? [userId, userId, targetId] : [userId, targetId];

    const result = Db.transaction(() => Db.prepare(sql).run(...params))();
    return result.changes > 0;
  } catch (error) {
    console.error(`[SQLite] 消息删除失败 | 类型:${chatType}`, {
      userId,
      targetId,
      error,
    });
    return false;
  }
}

// 更新消息
export function UpdateMessageFilePath(userId: number, uuid: string, localPath: string): boolean {
  try {
    const result = Db.prepare(
      `
                UPDATE message
                SET localPath = ?
                WHERE uuid = ?
                  AND ownerId = ?
                  AND messageType = ?
            `,
    ).run(localPath, uuid, userId, MessageType.file);
    return result.changes > 0;
  } catch (error) {
    console.error("更新文件消息失败", error);
    return false;
  }
}

// 查询全部聊天文件
export function FindAllMessageFile(userId: number, fileName: string): IMessageFileRes[] {
  try {
    const query = `
            SELECT fileName, fileUrl, fileSize, localPath, updatedAt
            FROM message
            WHERE ownerId = ?
              AND messageType = ?
              AND fileName LIKE ?
        `;
    const params = [userId, MessageType.file, `%${fileName}%`];
    return (Db.prepare(query).all(...params) as IMessageFileRes[]) || [];
  } catch (error) {
    console.error("获取我的文件失败:", error);
    return [];
  }
}

// 查询我的文件
export function GetMessageFileByOwner(userId: number): IMessageFileRes[] {
  try {
    const query = `
            SELECT fileName, fileUrl, fileSize, localPath, updatedAt
            FROM message
            WHERE ownerId = ?
              AND sendId = ?
              AND messageType = ?
        `;
    const params = [userId, userId, MessageType.file];
    return (Db.prepare(query).all(...params) as IMessageFileRes[]) || [];
  } catch (error) {
    console.error("获取我的文件失败:", error);
    return [];
  }
}

// 查询好友聊天文件
export function GetMessageFileByFriend(userId: number, sessionId: string): IMessageFileRes[] {
  try {
    const query = `
            SELECT uuId, fileName, fileUrl, fileSize, localPath, updatedAt
            FROM message
            WHERE ownerId = ?
              AND sessionId = ?
              AND chatType = ?
              AND messageType = ?
        `;
    const params = [userId, sessionId, ChatType.friend, MessageType.file];
    console.log("获取的参数为", params);

    return (Db.prepare(query).all(...params) as IMessageFileRes[]) || [];
  } catch (error) {
    console.error("获取我的文件失败:", error);
    return [];
  }
}

// 查询群聊天文件
export function GetMessageFileByGroup(userId: number, sessionId: string): IMessageFileRes[] {
  try {
    const query = `
            SELECT fileName, fileUrl, fileSize, localPath, updatedAt
            FROM message
            WHERE ownerId = ?
              AND sessionId = ?
              AND chatType = ?
              AND messageType = ?
        `;
    const params = [userId, sessionId, ChatType.group, MessageType.file];
    return (Db.prepare(query).all(...params) as IMessageFileRes[]) || [];
  } catch (error) {
    console.error("获取我的文件失败:", error);
    return [];
  }
}
